package utils.file;

import java.io.*;

public class FileTypeUtils {

    public static void main(String[] args) {
        File file = new File("/Users/lining/Desktop/pdftest/test.jpg");
        //file.renameTo(new File("/Users/lining/Desktop/pdftest/test.jpg"));
        System.out.println(file.getName());
        System.out.println(file.getPath());
        System.out.println(file.exists());
        System.out.println(file.isFile());
        //System.out.println(getFileTypeByFile(new File("/Users/lining/Desktop/pdftest/target.pdf")));
    }

    /**
     * 通过远程下载地址判断文件类型
     * @param remoteUrl
     * @return
     */
    public static String getFileTypeByRemoteUrl(String remoteUrl) {
        if (remoteUrl != null && remoteUrl.length() > 0) {
            int index = remoteUrl.lastIndexOf("/");
            if (index >= 0) {
                remoteUrl = remoteUrl.substring(index + 1);
                index = remoteUrl.lastIndexOf(".");
                if (index >= 0) {
                    String fileExtension = remoteUrl.substring(index + 1);
                    return fileExtension.toLowerCase();
                }
            }
        }
        return null;
    }

    public static String getFileTypeByFile(File file) {
        if(file.exists() && file.isFile()){
            InputStream is = null;
            try {
                byte[] b = new byte[50];
                is = new FileInputStream(file);
                is.read(b);
                return getFileTypeByStream(b);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                closeStream(is);
            }
        }
        return null;
    }

    public static void closeStream(Closeable closeable){
        if(closeable != null){
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getFileTypeByStream(byte[] b) {
        String fileHex = getFileHexString(b).toUpperCase();
        System.out.println(fileHex);
        FileTypeHexEnum[] enums = FileTypeHexEnum.values();
        for(FileTypeHexEnum hexEnum : enums){
            String fileTypeHex = hexEnum.getHex();
            if(fileHex.startsWith(fileTypeHex)){
                return hexEnum.getType();
            }
        }
        return null;
    }


    public static String getFileHexString(byte[] b) {
        if (b == null || b.length <= 0) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            int v = b[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
